package com.jiazhong.shixi.alipay.controller;
import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jiazhong.shixi.alipay.bean.Alipay;
import com.jiazhong.shixi.alipay.util.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin("*")
@RestController
@RequestMapping("/pay")
public class AlipayController {
    // 将application.yml中定义的参数声明到这里
    @Value("${appId}")
    private String appId;
    @Value("${privateKey}")
    private String privateKey;
    @Value("${publicKey}")
    private String publicKey;
    @Value("${notifyUrl}")
    private String notifyUrl;
    @Value("${returnUrl}")
    private String returnUrl;
    @Value("${signType}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${gatewayUrl}")
    private String gatewayUrl;

    @RequestMapping("/alipay")
    public String alipay(Alipay alipay) throws AlipayApiException {
        // 产生Alipay客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, "json", charset, publicKey, signType);
        // 调用支付宝接口
        AlipayTradePagePayRequest alipayTradeAppPayRequest = new AlipayTradePagePayRequest();
        // 设置付款成功后应跳转的路径
        alipayTradeAppPayRequest.setNotifyUrl(notifyUrl);
        alipayTradeAppPayRequest.setReturnUrl(returnUrl);
        // 设置支付宝的各项参数
        String json = JSONArray.toJSONString(alipay);
        alipayTradeAppPayRequest.setBizContent(json);
        System.out.println("支付的参数是：" + json);
        System.out.println(JSONArray.toJSONString(alipayTradeAppPayRequest));
        // 生成最终的订单
        return alipayClient.pageExecute(alipayTradeAppPayRequest).getBody();
    }

    @RequestMapping("/success")
    public JsonResult success() {
        JsonResult result = new JsonResult(true, 200, "支付成功", "");
        return result;
    }
}
